from typing import TYPE_CHECKING

from PySide6.QtGui import QColor

from gui.signals import SIGNALS
from utils.db import DBSession
from utils.reference import ValueRange, fast_json

if TYPE_CHECKING:
    from common.player.reference import Player

EQUIPMENT_SLOTS = (
    'weapon',
    'titles', 'badges', 'ring', 'bracelets', 'pendants',
    'helmet', 'torso', 'limbs', 'shoes', 'gloves',
)


class Equipment:
    def __init__(self, key, **kwargs):
        self.key = key
        self.slot = kwargs['slot']
        self.name = kwargs['name']
        self.price = kwargs['price']
        self.rank = kwargs.get('rank', 'F')
        self.durability = ValueRange(100)
        self.level = kwargs['level']
        # 属性
        self.attrs = dict()

        self.quality = 'average'
        self.star_level = 0
        self.enchantments = []
        self.strengthen = 0  # 强化
        self.plugins = []
        self.traits = []

    def __json__(self):
        return fast_json(self)

    def display_star(self, step=4):
        result = ''
        if stars := '★' * self.star_level:
            result += ' ' + ' '.join(stars[i:i + step] for i in range(0, len(stars), step))

        return result

    def quality_color(self):
        return QColor(DBSession.colors[self.quality])

    def overview(self, show_durability=True):
        color = self.quality_color()
        name = f'<span style="color: {color.name()}">{self.name}</span>'
        prefix = f'【{self.rank}{('-' + str(self.strengthen)) if self.strengthen > 0 else ""}】'

        result = f'{prefix}{name}{self.display_star()}'
        if show_durability:
            result += f' {self.durability}'

        return result

    def dialog_content(self):
        rows = [
            ('星级', self.star_level),
            ('位阶', self.rank),
            ('等级需求', self.level),
            ('类型', DBSession.tr[self.slot]),
            ('强化', self.strengthen),
            ('品质', f'<span style="color: {self.quality_color().name()}">{self.quality}</span>'),
            ('耐久', self.durability),
            ('价值', self.price)
        ]

        if self.enchantments:
            rows.append((
                '附魔',
                [enchant for enchant in self.enchantments]
            ))

        if self.plugins:
            rows.append((
                '插件',
                [plugin for plugin in self.plugins]
            ))

        return rows

    def install(self, player: 'Player'):
        player.bag.cap.current -= 1
        SIGNALS.update_main_ui.emit()

    def uninstall(self, player: 'Player'):
        player.bag.cap.current += 1
        SIGNALS.update_main_ui.emit()
